﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
using Abp0713Demo.Materials.Dto;
using Abp0713Demo.Users.Dto;

namespace Abp0713Demo.Materials
{
    public class MaterialAppService : ApplicationService ,IMaterialAppService
    {
        private IRepository<MaterialInfo> _materialsRepository;

        public MaterialAppService(IRepository<MaterialInfo> materialsRepository)
        {
            _materialsRepository = materialsRepository;
        }

        public async Task Create(CreateOrUpdateMaterialInput input)
        {
            await _materialsRepository.InsertAsync(new MaterialInfo()
            {
                Name = input.Name,
                BatchNumber = input.BatchNumber,
                Code = input.Code,
                OriginAddress = input.OriginAddress
            });
        }

        public async Task Update(CreateOrUpdateMaterialInput input)
        {
            var info =await _materialsRepository.GetAsync(input.Id);
            if(info == null) 
                throw new Exception("查无此信息");

            info.Name = input.Name;
            info.BatchNumber = input.BatchNumber;
            info.Code = input.Code;
            info.OriginAddress = input.OriginAddress;

            await _materialsRepository.UpdateAsync(
                info);

        }

        public async Task Delete(int id)
        {
            await _materialsRepository.DeleteAsync(id);
        }

        public async Task<PagedResultDto<MaterialListDto>> PagedList(MaterialListRequestDto input)
        {
            var query = _materialsRepository.GetAll();
            var count = await query.CountAsync();
            var list = await query
                .OrderBy(x => input.Sorting)
                .PageBy(input)
                .ToListAsync();

            var materialListDtos = list.MapTo<List<MaterialListDto>>();

            return new PagedResultDto<MaterialListDto>(
                count,
                materialListDtos
                );

        }

        public async Task<UpdateMaterialOutput> GetInfo(int id)
        {
            var info = await _materialsRepository.GetAsync(id);
            if (info == null)
                throw new Exception("查无此信息");


            return info.MapTo<UpdateMaterialOutput>();
        }
    }
}